package com.lxn.course.service.impl;
import com.lxn.course.vo.CrumbsVO;
import com.lxn.feignclients.PageStaticFeignClient;
import com.lxn.hrm.constants.RedisKeyConstants;
import com.alibaba.fastjson.JSON;
import com.lxn.course.domain.CourseType;
import com.lxn.course.mapper.CourseTypeMapper;
import com.lxn.course.service.ICourseTypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lxn.hrm.feignclients.RedisFeignClient;
import com.lxn.hrm.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {

    @Autowired
    private RedisFeignClient redisFeignClient;
    @Autowired
    private PageStaticFeignClient pageStaticFeignClient;
    @Override
    public boolean insert(CourseType entity) {
        boolean insertSuccess = super.insert(entity);
        resetRedisForCourseType();
        triggerPageStatic();
        return insertSuccess;
    }

    @Override
    public boolean deleteById(Serializable id) {
        boolean deleteSuccess = super.deleteById(id);
        resetRedisForCourseType();
        triggerPageStatic();
        return deleteSuccess;
    }

    @Override
    public boolean updateById(CourseType entity) {
        boolean updateSuccess = super.updateById(entity);
        resetRedisForCourseType();
        triggerPageStatic();
        return updateSuccess;
    }

    //触发课程首页页面静态化
    public void triggerPageStatic(){
        //准备数据
        List<CourseType> courseTypes = this.treeData();
        String pageName = "home";
        //封装数据的Map
        Map<String,Object> model = new HashMap<>();
        model.put("courseType",courseTypes);
        AjaxResult ajaxResult = redisFeignClient.set(RedisKeyConstants.COURSE_TYPES_PAGE_STATIC, JSON.toJSONString(model));
        if(ajaxResult.isSuccess()){
            throw new RuntimeException("页面静态化页面数据准备失败："+ajaxResult.getMessage());
        }
        AjaxResult result = pageStaticFeignClient.pageStatic(pageName, RedisKeyConstants.COURSE_TYPES_PAGE_STATIC);
        if(!result.isSuccess()){
            throw new RuntimeException("页面静态化失败："+result.getMessage());
        }

    }

    private  List<CourseType>  resetRedisForCourseType(){
        List<CourseType> courseTypes = baseMapper.selectList(null);
        redisFeignClient.set(RedisKeyConstants.COURSE_TYPE,JSON.toJSONString(courseTypes));
        return courseTypes;
    }

    @Override
    public List<CourseType> treeData() {
        List<CourseType> courseTypes = null;
        AjaxResult ajaxResult = redisFeignClient.get(RedisKeyConstants.COURSE_TYPE);
        if(ajaxResult.isSuccess() && null != ajaxResult.getResultObj()){
            String jsonFromRedis = ajaxResult.getResultObj().toString();
            courseTypes = JSON.parseArray(jsonFromRedis , CourseType.class);
        }else{
            courseTypes = resetRedisForCourseType();
        }
        List<CourseType> primaryCourseType = new ArrayList<>();
        for(CourseType courseType : courseTypes){
            if(courseType.getPid().longValue() == 0){
                primaryCourseType.add(courseType);
            }else{
                CourseType currentPrimaryCourseType = null;
                for(CourseType pcourseType : courseTypes ){
                    if(courseType.getPid().longValue() == pcourseType.getId().longValue()){
                        currentPrimaryCourseType = pcourseType;
                        break;
                    }
                }
                if(currentPrimaryCourseType != null){
                    currentPrimaryCourseType.getChildren().add(courseType);
                }
            }
        }
        return primaryCourseType;
    }

    @Override
    public List<CrumbsVO> crumbs(Long id) {
        //查询所有父分类
        CourseType currentCourseType = baseMapper.selectById(id);
        //获取父分类
        String path = currentCourseType.getPath();
        path = path.startsWith(".")?path.substring(1):path;
        path = path.endsWith(".")?path.substring(0,path.length()-1):path;
        //获取所有父分类
        String[] types = path.split("\\.");

        List<CrumbsVO> result = new ArrayList<>();
        for(String type : types ){
            CrumbsVO vo = new CrumbsVO();
            Long typeId = Long.valueOf(type);
            CourseType courseType = baseMapper.selectById(typeId);

            vo.setOwnerProductType(courseType);

            //每个分类同级分类，设置CrumbsVO.otherProductTypes
            Long pid = courseType.getPid();
            List<CourseType> otherCoutseTypes = baseMapper.selectByPid(pid);

            //删除自己
            Iterator<CourseType> iterator = otherCoutseTypes.iterator();
            while (iterator.hasNext()){
                if(iterator.next().getId().equals(courseType.getId())){
                    iterator.remove();
                    break;
                }
            }
            vo.setOtherProductTypes(otherCoutseTypes);
            result.add(vo);
        }
        return result;
    }
}
